package com.yun.util.yun.leetCode.medium;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StraightHand {

    public boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length<1||hand.length>10000||hand.length % groupSize!=0){ return false;}
        if (groupSize>hand.length||groupSize<1){ return false;}
        for (int i : hand) {
            if (i<1||i>100000000){ return false; }
        }
        this.maopaosort(hand);
        List<Integer> collect = Arrays.stream(hand).boxed().collect(Collectors.toList());
        try {
            boolean deal = deal(collect, groupSize);
            if (deal){
                return true;
            }
        }catch (Exception e){
            return false;
        }
        return false;
    }

    private boolean deal(List<Integer> collect,int groupSize) {
        int rs = 1;
        int temp = collect.get(collect.size() - 1);
        int count = 0;
        for (int i = collect.size() - 1; i >= 0; i--) {
            Integer integer = collect.get(i);
            if (integer != temp){
                continue;
            }
            collect.remove(integer);
            count = count+1;
            if (count == groupSize){
                if (collect.size()==0){
                    rs = 2;
                    break;
                }
                deal(collect, groupSize);
            }
            temp = temp-1;
        }
        return rs == 2;
    }


    private void maopaosort(int[] a) {
        for(int i=a.length-1;i>=0;i--)
        {
            for(int j=0;j<i;j++)
            {
                if(a[j]>a[j+1])
                {
                    int team=a[j];
                    a[j]=a[j+1];
                    a[j+1]=team;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,6,2,3,4,7,8};
        int b = 3;
        StraightHand hand = new StraightHand();
        boolean rs = hand.isNStraightHand(a, b);
        System.out.println(rs);
    }
}
